package com.nervenets.web.controller.handler.admin.setting;

import com.nervenets.utils.JodaUtils;
import com.nervenets.utils.StringUtils;
import com.nervenets.web.controller.Global;
import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.Role;
import com.nervenets.web.hibernate.domain.setting.Tags;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

public class TagEditHandler extends SessionHandler<TagEditParams> {
    @Override
    public ArrayList<Role> allowRoles() {
        return Role.administrator();
    }

    @Override
    public boolean needLog() {
        return false;
    }

    @Override
    public String handle(TagEditParams params, HttpServletRequest request) throws Exception {
        Tags tags = new Tags();
        if (params.getTagId() > 0) {
            tags = userDao.findByIdIgnoreRemoved(params.getTagId(), Tags.class);
            if (null == tags) return errorMessage(MessageCode.code_404, "没有找到修改的标签");
            if (!tags.getTagType().equals(params.getTagType())) {
                return errorMessage(MessageCode.code_444, "相应标签的版块或类型不符");
            }
        }
        tags.setTagType(params.getTagType());
        tags.setName(params.getName());
        if (!StringUtils.isEmpty(params.getIcon())) {
            tags.setIcon(params.getIcon());
        }
        tags.setQueue(params.getQueue());
        tags.setRemoved(params.isEnable() ? 0 : JodaUtils.getTimestamp());
        userDao.saveOrUpdate(tags);
        globalService.setGlobalPair(Global.Constants.TAGS_KEY, "");
        return successMessage(tags);
    }

    @Override
    public String result() throws Exception {
        return null;
    }
}
